
#include <assert.h>
#include "HrkNode.h"

IMPLEMENT_DYNCREATE( CHrkNode,CHrkObject )

CHrkNode::CHrkNode()
{
	m_object = NULL;
}

CHrkNode::~CHrkNode()
{
}

void CHrkNode::AttachChild( CHrkNode* ch )
{
	int slot = ch->GetSlotIndex( );
	
	if( slot == -1 ){
		ch->m_parent = this;
		ch->m_slot = m_child_list.Count();
		m_child_list.push_back( ch );
	}
}

void CHrkNode::DetachChild( CHrkNode* ch )
{
	int slot = ch->GetSlotIndex( );
	
	if( slot == -1 ){
		ch->m_parent = NULL;
		ch->m_slot = -1;
		m_child_list.erase( m_child_list.begin()+slot);
	}
}

void CHrkNode::UpdateTransform()
{
	CHrkObject* parent = m_parent;

	m_mat.Compose( m_translate,m_rotate,m_scale );

	if(parent){
		m_mat_comb = m_mat*parent->m_mat_comb;
	}
	else{
		m_mat_comb = m_mat;
	}
	
	int nChilds = m_child_list.Count();
	for( int i = 0;i<nChilds;i++ ){
		m_child_list[i]->UpdateTransform();	
	}
	
	if( m_object ){
		m_object->m_mat_comb  = m_mat_comb;
	}
}

void CHrkNode::ParseScript( TiXmlElement* elem )
{
	m_name = elem->Attribute( "name");
	TiXmlElement* e = elem->FirstChildElement( "TransformMatrix");
	const char* s = e->Attribute( "translation" );
	sscanf(s, "%f,%f,%f;", &m_translate.x, &m_translate.y, &m_translate.z);

	s = e->Attribute( "rotation" );
	sscanf(s, "%f,%f,%f;", &m_rotate.x, &m_rotate.y, &m_rotate.z);

	s = e->Attribute( "scale" );
	sscanf(s, "%f,%f,%f;", &m_scale.x, &m_scale.y, &m_scale.z);

	m_translate1 = m_translate;
	m_rotate1 = m_rotate;
	m_scale1 = m_scale;

	s = e->GetText();

	sscanf(s,"%f,%f,%f,%f,"
		"%f,%f,%f,%f,"
		"%f,%f,%f,%f,"
		"%f,%f,%f,%f",
		&m_mat.x.x,&m_mat.x.y,&m_mat.x.z,&m_mat.x.w,
		&m_mat.y.x,&m_mat.y.y,&m_mat.y.z,&m_mat.y.w,
		&m_mat.z.x,&m_mat.z.y,&m_mat.z.z,&m_mat.z.w,
		&m_mat.w.x,&m_mat.w.y,&m_mat.w.z,&m_mat.w.w
		);

	if( m_object ){
		m_object->ParseScript( elem );
	}
}

void CHrkNode::Destroy()
{
	int nChilds = m_child_list.Count();
	for( int i = 0;i<nChilds;i++ ){

	}
}